package com.neonbacon.snake;

import java.util.Random;
import java.util.Timer;
import java.util.TimerTask;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;

public class Level {
	int[] map;
	int lwidth;
	int lheight;
	int tileHeight;
	EntitySnake s;
	Timer updateTimer;
	Bitmap food;

	int foodpos;

	public Level(Context c, int width, int height, int tileHeight) {
		this.tileHeight = tileHeight;
		food = Bitmap
				.createScaledBitmap(
						BitmapFactory.decodeResource(c.getResources(),
								R.drawable.food),
						BitmapFactory.decodeResource(c.getResources(),
								R.drawable.food).getWidth() / 2,
						BitmapFactory.decodeResource(c.getResources(),
								R.drawable.food).getHeight() / 2, true);
		lwidth = Math.round(width / tileHeight) + 1;
		lheight = Math.round(height / tileHeight) -1;
		map = new int[lwidth * lheight];
		for (int x = 0; x != lwidth; x++) {
			for (int y = 0; y != lheight; y++) {
				map[x + y * lwidth] = 1;
			}
		}
		s = new EntitySnake(0, 8, c, this);
		new Thread(new Runnable(){	
			public void run(){
				updateTimer = new Timer("UPDATE");
				updateTimer.schedule(new TimerTask() {
					@Override
					public void run() {
						Level.this.update();
					}
				}, 1000, 500);
			}
		}).start();
		
		onFoodEat();
	}

	public void update() {
		s.update();
	}

	public void onFoodEat() {
		Random random = new Random();
		int pos = random.nextInt(((lwidth - 1)* (lheight - 1)));
		map[pos] = 2;
		foodpos = pos;
		ScoreView.score++;
	}

	public void draw(Canvas c) {
		Paint paint = new Paint();
		paint.setStyle(Paint.Style.STROKE);
		paint.setStrokeWidth(2);
		paint.setColor(Color.WHITE);

		for (int x = 0; x != lwidth; x++) {
			for (int y = 0; y != lheight; y++) {
				if (map[x + y * lwidth] == 1) {
					c.drawRect(new Rect(x * tileHeight, y * tileHeight,
							tileHeight, tileHeight), paint);
				}
				if (map[x + y * lwidth] == 2) {
					c.drawBitmap(food, x * tileHeight, y * tileHeight, null);
				}

			}
		}

		s.render(c);
	}
}